﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuanLySieuThi.Controllers
{
    public class Helper<T>
    where T : new()
    {
        public List<T> TableToList(DataTable table)
        {
            List<T> list = new List<T>();
            for (int i = 0; i < table.Rows.Count; i++)
            {
                T t = new T();
                foreach (var item in t.GetType().GetProperties())
                {
                    if (table.Columns.Contains(item.Name))
                    {
                        if (table.Rows[i][item.Name].ToString().Length > 0)
                        {
                            t.GetType().GetProperty(item.Name).SetValue(t, table.Rows[i][item.Name]);
                        }
                    }
                }
                list.Add(t);
            }
            return list;
        }

        public DataTable ListToTable(List<T> list)
        {
            T t = new T();
            DataTable table = new DataTable();
            foreach (var item in t.GetType().GetProperties())
                table.Columns.Add(item.Name);

            foreach (var item in list)
            {
                List<string> p = new List<string>();
                foreach (var proper in item.GetType().GetProperties())
                    p.Add(proper.GetValue(item).ToString());
                table.Rows.Add(p.ToArray());
            }
            return table;
        }
    }
}
